<template>
  <div class="app-container">
    <el-form :model="queryParams" :disabled="loading" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="演练主题" prop="drillThemes">
        <el-input
          v-model="queryParams.drillThemes"
          placeholder="请输入演练主题"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:drill:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:drill:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:drill:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="drillList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="演练主题" align="center" prop="drillThemes" />
      <el-table-column label="演练地点" align="center" prop="address" />
      <el-table-column label="演练时间" align="center" prop="drillTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.drillTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="演练方案" align="center" prop="drillProject" />
      <el-table-column label="创建人" align="center" prop="createrName" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" align="center" prop="operterName" />
      <el-table-column label="操作时间" align="center" prop="operTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.operTime, '{y}-{m}-{d} {h}:{m}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:drill:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:drill:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改应急演练对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="演练主题" prop="drillThemes">
          <el-input v-model="form.drillThemes" placeholder="请输入演练主题" />
        </el-form-item>
        <el-form-item label="演练时间" prop="drillTime">
          <el-date-picker clearable
            v-model="form.drillTime"
            type="datetime"
            value-format="yyyy-MM-dd hh:mm:ss"
            placeholder="请选择演练时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="演练地点" prop="address">
          <el-input v-model="form.address" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="演练方案" prop="drillProject">
          <el-input v-model="form.drillProject" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="演练培训" prop="train">
          <el-upload
            :action="uploadUrl"
            :file-list="form.train"
            :on-success="(res, file, fileList) => uploadImgSuccess(res, file, fileList, 'train')"
            :on-preview="uploadPreview"
            :before-upload="file => uploadBefore(file, 'train')"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">文件大小不能超过5M</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="演练照片" prop="photo">
          <el-upload
            :action="uploadUrl"
            :file-list="form.photo"
            list-type="picture-card"
            :on-success="(res, file, fileList) => uploadImgSuccess(res, file, fileList, 'photo')"
            :before-upload="file => uploadBefore(file, 'photo')"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="演练评估" prop="assess">
          <el-upload
            :action="uploadUrl"
            :file-list="form.assess"
            :on-success="(res, file, fileList) => uploadImgSuccess(res, file, fileList, 'assess')"
            :before-upload="file => uploadBefore(file, 'assess')"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">文件大小不能超过5M</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="演练总结" prop="summary">
          <el-upload
            :action="uploadUrl"
            :file-list="form.summary"
            :on-success="(res, file, fileList) => uploadImgSuccess(res, file, fileList, 'summary')"
            :before-upload="file => uploadBefore(file, 'summary')"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">文件大小不能超过5M</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="持续改进" prop="improve">
          <el-upload
            :action="uploadUrl"
            :file-list="form.improve"
            :on-success="(res, file, fileList) => uploadImgSuccess(res, file, fileList, 'improve')"
            :before-upload="file => uploadBefore(file, 'improve')"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">文件大小不能超过5M</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDrill, getDrill, delDrill, addDrill, updateDrill } from "@/api/system/drill";
import {uploadUrl, uploadFile, rootPath} from "@/api/system/config";
export default {
  name: "Drill",
  data() {
    return {
      uploadUrl,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 应急演练表格数据
      drillList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        drillTime: null,
        address: null,
        drillThemes: null,
        drillProject: null,
        creater: null,
        operTime: null,
        operter: null
      },
      // 表单参数
      form: {
        train: [],
        photo: [],
        assess: [],
        summary: [],
        improve: []
      },
      // 表单校验
      rules: {
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    uploadPreview(file) {
      console.log('file', file)
      window.open(rootPath + file.fileUrl, '_blank');
    },
    uploadBefore(file, type) {
      console.log('file', file)
      const isLt2M = file.size / 1024 / 1024 < 5;

      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 5MB!');
      }
      if(['photo'].includes(type)) {
        const isJPG = ['image/jpeg', 'image/png'].includes(file.type);
        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG,PNG 格式!');
        }
        return isJPG && isLt2M
      }
      return isLt2M;
    },
    uploadImgSuccess(res, file, fileList, type) {
      console.log('res', res, file, fileList)
      let typeTmp
      switch (type) {
        case 'train':
          typeTmp = 4
          break
        case 'photo':
          typeTmp = 5
          break
        case 'assess':
          typeTmp = 6
          break
        case 'summary':
          typeTmp = 7
          break
        case 'improve':
          typeTmp = 8
          break
        default:
      }
      this.form[type] = [
        ...this.form[type],
        ...[
          {
            name: res.originalFilename,
            fileType: typeTmp,
            url: res.url,
            fileUrl: res.fileName
          }
        ]
      ]
    },
    /** 查询应急演练列表 */
    getList() {
      this.loading = true;
      listDrill(this.queryParams).then(response => {
        this.drillList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        drillTime: null,
        address: null,
        drillThemes: null,
        drillProject: null,
        createTime: null,
        creater: null,
        operTime: null,
        operter: null,
        train: [],
        photo: [],
        assess: [],
        summary: [],
        improve: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加应急演练";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDrill(id).then(response => {
        this.form = response.data;
        this.form.train = []
        this.form.photo = []
        this.form.assess = []
        this.form.summary = []
        this.form.improve = []
        for(let i = 0; i < this.form.fileList.length; i++) {
          const fileItem = this.form.fileList[i]
          if (!fileItem.fileUrl) continue
          const tmpArr = fileItem.fileUrl.split('/')
          fileItem.name = tmpArr[tmpArr.length - 1]
          const tmpArr1 = fileItem.name.split('.')
          fileItem.extname = tmpArr1[tmpArr1.length - 1]
          fileItem.url = rootPath + fileItem.fileUrl
          if (this.form.fileList[i].fileType === 4) {
            this.form.train = [
              ...this.form.train,
              ...[fileItem]
            ]
          }
          if (this.form.fileList[i].fileType === 5) {
            this.form.photo = [
              ...this.form.photo,
              ...[fileItem]
            ]
          }
          if (this.form.fileList[i].fileType === 6) {
            this.form.assess = [
              ...this.form.assess,
              ...[fileItem]
            ]
          }
          if (this.form.fileList[i].fileType === 7) {
            this.form.summary = [
              ...this.form.summary,
              ...[fileItem]
            ]
          }
          if (this.form.fileList[i].fileType === 8) {
            this.form.improve = [
              ...this.form.improve,
              ...[fileItem]
            ]
          }
        }
        this.open = true;
        this.title = "修改应急演练";
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log('form', this.form)
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.fileList = []
          this.form.fileList = [
            ...this.form.train,
            ...this.form.photo,
            ...this.form.assess,
            ...this.form.summary,
            ...this.form.improve,
          ]
          if (this.form.id != null) {
            updateDrill(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDrill(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除应急演练编号为"' + ids + '"的数据项？').then(function() {
        return delDrill(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/drill/export', {
        ...this.queryParams
      }, `drill_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
